package com.example.oppotest.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NetUtils {
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    public Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * url请求
     *
     * @param strUrl
     *            请求url
     *
     * @param params
     *            请求map参数
     *
     * @param method
     *            请求方式
     *
     * @return String 返回结果
     *
     */
    public static String request(String strUrl, Map<String, Object> params, String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;

        try {
            StringBuffer sb = new StringBuffer();

            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }

            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();

            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }

            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    /**
     * url请求
     *
     * @param strUrl
     *            请求url
     *
     * @param body
     *            body请求参数
     *
     * @return String 返回结果
     *
     */
    public static String postByRaw(String strUrl, String body) throws IOException {
        @SuppressWarnings({ "resource" })
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(strUrl);
        StringEntity postingString = new StringEntity(body, "UTF-8");
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String ret = EntityUtils.toString(response.getEntity());

        return ret;
    }

    /*
    *
    * 取自AdConvTest.java
    *
    * */
    public static String doPostEntityJSON(String url, Object postReq) {
        RequestConfig requestCong = RequestConfig.custom().setConnectionRequestTimeout(5000)
                .setConnectTimeout(5000).setSocketTimeout(5000).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestCong);
        httpPost.setEntity(new StringEntity(JSON.toJSONString(postReq), ContentType.APPLICATION_JSON));

        CloseableHttpClient httpClient = HttpClients.custom().setMaxConnTotal(100).setMaxConnPerRoute(100).setRetryHandler(
                new DefaultHttpRequestRetryHandler(0, false)).disableAutomaticRetries().build();

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpPost);
            return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            return null;
        }
    }

    public static String postXwwFormUrlEncoded(String url, String token, HashMap<String, String> paraMap) throws IOException {
        List<NameValuePair> params = new ArrayList<>();
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String msg = "";
        try {
            if (paraMap != null && paraMap.size() != 0) {
                for (Map.Entry<String, String> entry : paraMap.entrySet()) {
                    params.add(new NameValuePair() {
                        @Override
                        public String getName() {
                            return entry.getKey();
                        }
                        @Override
                        public String getValue() {
                            return entry.getValue();
                        }
                    });
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("Authorization", "Bearer " + token);
            HttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (HttpURLConnection.HTTP_OK == statusCode) {
                HttpEntity entity = response.getEntity();
                msg = EntityUtils.toString(entity);
            }else {
                return "{\"status\": \"0\",\"desc\": \"接口请求异常\"}";
            }
        } catch (IOException e) {
            throw e;
        }
        return msg;
    }


    /**
     * url请求2
     *
     * @param strUrl
     *            请求url
     *
     * @param params
     *            请求map参数
     *
     * @return String 返回结果
     *
     */
    public static String requestUrl(String strUrl, Map<String, Object> params) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;

        try {
            StringBuffer sb = new StringBuffer();
            URL url = new URL(strUrl + "?" + urlencode(params));
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead + "\r\n");
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    /**
     * url参数编码
     *
     * @param data
     *            map参数
     *
     * @return String 编码后的字符串
     *
     */
    public static String urlencode(Map<String, Object> data) {
        StringBuilder sb = new StringBuilder();

        for (Map.Entry<String, Object> i : data.entrySet()) {
            sb.append(i.getKey()).append("=").append(i.getValue()).append("&");
        }

        return sb.toString().substring(0, sb.toString().length()-1);
    }

    /**
     * url参数编码
     *
     * @param data
     *            map参数
     *
     * @return String 编码后的字符串
     *
     */
    public static String urlencodeByString(Map<String, String> data) {
        StringBuilder sb = new StringBuilder();

        for (Map.Entry<String, String> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return sb.toString().substring(0, sb.toString().length()-1);
    }

    /**
     * 获取浏览器客户端ip地址
     *
     * @param request
     *            请求对象
     *
     * @return String ip地址
     *
     */
    public static String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        } else {
            ip = request.getHeader("X-Forwarded-For");
            if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            } else {
                ip = request.getHeader("Proxy-Client-IP");
                if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
                    return ip;
                } else {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                    if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
                        return ip;
                    } else {
                        ip = request.getRemoteAddr();
                        return ip;
                    }
                }
            }
        }
    }

    /**
     * 判断浏览器是否是移动端
     *
     * @param request
     *            请求对象
     *
     * @return Boolean 是否是移动端
     *
     */
    public static Boolean isMobile(HttpServletRequest request) {
        String ua = request.getHeader("User-Agent");

        String[] agent = { "Android", "iPhone", "iPod","iPad", "Windows Phone", "MQQBrowser" };

        boolean flag = false;
        if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
            if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
                for (String item : agent) {
                    if (ua.contains(item)) {
                        flag = true;
                        break;
                    }
                }
            }
        }

        return flag;
    }

    public static JSONObject getJSONParam(HttpServletRequest request){
        JSONObject jsonParam = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

            // 数据写入Stringbuilder
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            jsonParam = JSONObject.parseObject(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonParam;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String url = "https%3A%2F%2Fwww.baidu.com%3Faa%3Dbb%26cc%3Ddd%26ee%3Dff%26gg%3Dhh%26s%3D7FBAFDD1-A695-41DA- 96F8-8M0zEg7wCZFmCE949L290%26c%3DQSL2E4TE3MGUtMTFlOS1hNjJiRjYTkwNDc3MjczNGRjYzhkZTA4NTRkIgExKgt2M4ZGUwODU0ZDpAMzQSL2E4MzgwZmE4LTE3MGU";
        System.out.println(URLDecoder.decode(url, "UTF-8"));
    }

}
